/*
 * This file is part of aion-emu <aion-emu.com>.
 *
 *  aion-emu is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  aion-emu is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with aion-emu.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.aionemu.gameserver.utils.gametime;

import org.apache.log4j.Logger;

import com.aionemu.commons.database.dao.DAOManager;
import com.aionemu.commons.utils.AionThread;
import com.aionemu.gameserver.dao.GameTimeDAO;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.network.aion.serverpackets.SM_GAME_TIME;
import com.aionemu.gameserver.utils.PacketSendUtility;
import com.aionemu.gameserver.utils.ThreadPoolManager;
import com.aionemu.gameserver.world.World;

/**
 * Manages ingame time
 * 
 * @author Ben
 * 
 */
public class GameTimeManager
{
	private static final Logger		log				= Logger.getLogger(GameTimeManager.class);
	private static GameTime			instance;
	private static GameTimeUpdater	updater;
	private static boolean			clockStarted	= false;

	private final static int		GAMETIME_UPDATE	= 3 * 60000;
	
	private static final long gameStarted = System.currentTimeMillis();
	private static volatile int gameTicks;

	public static final int TICKS_PER_SECOND = 10;
	public static final int MILLIS_IN_TICK = 1000 / TICKS_PER_SECOND;

	static
	{
		GameTimeDAO dao = DAOManager.getDAO(GameTimeDAO.class);
		instance = new GameTime(dao.load());
	}

	/**
	 * Gets the current GameTime
	 * 
	 * @return GameTime
	 */
	public static GameTime getGameTime()
	{
		return instance;
	}

	/**
	 * Starts the counter that increases the clock every tick
	 * 
	 * @throws IllegalStateException
	 *             If called twice
	 */
	public static void startClock()
	{
		if (clockStarted)
		{
			throw new IllegalStateException("Clock is already started");
		}

		updater = new GameTimeUpdater(getGameTime());
		ThreadPoolManager.getInstance().scheduleAtFixedRate(updater, 0, 5000);
		startGameTimeSend();
		clockStarted = true;
	}

	/**
	 * Saves the current time to the database
	 * 
	 * @return Success
	 */
	public static boolean saveTime()
	{
		stopTimer();
		log.info("Game time saved...");
		return DAOManager.getDAO(GameTimeDAO.class).store(getGameTime().getTime());
	}

	public static void startGameTimeSend()
	{
		/**
		 * Update players with current game time
		 */
		ThreadPoolManager.getInstance().scheduleAtFixedRate(new Runnable()
		{

			@Override
			public void run()
			{
				log.debug("Sending current game time to all players");
				for (Player player : World.getInstance().getAllPlayers())
				{
					PacketSendUtility.sendPacket(player, new SM_GAME_TIME());
				}
			}
		}, GAMETIME_UPDATE, GAMETIME_UPDATE);

		log.debug("GameTimeService started. Update interval:" + GAMETIME_UPDATE);

	}
	
	public static int getGameTicks()
	{
		return gameTicks;
	}
	
	private static void stopTimer()
	{
		try
		{
			timingThread.shutdown();
		}
		catch (InterruptedException e)
		{
			e.printStackTrace();
		}
	}

	private static final TimingThread timingThread = new TimingThread();
	
	private static final class TimingThread extends AionThread
	{
		private TimingThread()
		{
			super("TimingThread");
			setPriority(Thread.MAX_PRIORITY);
			setDaemon(true);
			
			start();
		}
		
		@Override
		protected void runTurn()
		{
			gameTicks = (int)((System.currentTimeMillis() - gameStarted) / MILLIS_IN_TICK);
		}
		
		@Override
		protected void sleepTurn() throws InterruptedException
		{
			long delay = gameStarted + (gameTicks + 1) * MILLIS_IN_TICK - System.currentTimeMillis();
			
			if (delay > 0)
				Thread.sleep(delay);
		}
	}
}
